package com.avoscloud.chat.service;

import android.content.Context;

import com.avos.avoscloud.*;
import com.example.studycard.R;
import com.avoscloud.chat.avobject.AddRequest;
import com.avoscloud.chat.base.App;
import com.avoscloud.chat.base.C;
import com.avoscloud.chat.util.SimpleNetTask;
import com.avoscloud.chat.util.Utils;

import java.util.List;

/**
 *获取对应用户好友请求的数量
 */
public class AddRequestService {
	public static int countAddRequests() throws AVException {
		AVQuery<AddRequest> q = AVObject.getQuery(AddRequest.class);
		q.setCachePolicy(AVQuery.CachePolicy.NETWORK_ELSE_CACHE);//若无网络时直接从缓存获取
		q.whereEqualTo(AddRequest.TO_USER, AVUser.getCurrentUser());
		try {
			return q.count();
		} catch (AVException e) {
			if (e.getCode() == AVException.CACHE_MISS) {
				return 0;
			} else {
				throw e;
			}
		}
	}

	public static List<AddRequest> findAddRequests() throws AVException {
		AVUser user = AVUser.getCurrentUser();
		AVQuery<AddRequest> q = AVObject.getQuery(AddRequest.class);
		q.include(AddRequest.FROM_USER);
		q.whereEqualTo(AddRequest.TO_USER, user);
		q.orderByDescending(C.CREATED_AT);
		q.setCachePolicy(AVQuery.CachePolicy.NETWORK_ELSE_CACHE);
		return q.find();
	}
/*
 * Preference，首选项，自动保存上次点击的这些数据，并立时生效，以便下次应用调起的时候直接使用
 */
	public static boolean hasAddRequest() throws AVException {
		PreferenceMap preferenceMap = PreferenceMap.getMyPrefDao(App.ctx);//从缓存中获取好友请求
		int addRequestN = preferenceMap.getAddRequestN();//获取上次好友请求次数
		int requestN = countAddRequests();//刷新后再次获取的好友请求次数
		if (requestN > addRequestN) {//说明有新的请求
			return true;
		} else {
			return false;
		}
	}

	public static void agreeAddRequest(final AddRequest addRequest,
			final SaveCallback saveCallback) {
		UserService.addFriend(addRequest.getFromUser().getObjectId(),
				new SaveCallback() {
					@Override
					public void done(AVException e) {
						if (e != null) {
							if (e.getCode() == AVException.DUPLICATE_VALUE) {
								addRequest.setStatus(AddRequest.STATUS_DONE);
								addRequest.saveInBackground(saveCallback);
							} else {
								saveCallback.done(e);
							}
							try {
								createAddRequest(addRequest.getFromUser());
							} catch (Exception e1) {
								// TODO Auto-generated catch block
								e1.printStackTrace();
							}
						} else {
							addRequest.setStatus(AddRequest.STATUS_DONE);
							addRequest.saveInBackground(saveCallback);
						}
					}
				});
	}

	public static void createAddRequest(AVUser toUser) throws Exception {
		AVUser curUser = AVUser.getCurrentUser();//获取当前用户
		/*
		 * 根据当前用户和所要添加的用户还有请求状态去数据库表AddRequest中查询是否已存在该请求
		 */
		AVQuery<AddRequest> q = AVObject.getQuery(AddRequest.class);
		q.whereEqualTo(AddRequest.FROM_USER, curUser);
		q.whereEqualTo(AddRequest.TO_USER, toUser);
		q.whereEqualTo(AddRequest.STATUS, AddRequest.STATUS_WAIT);
		int count = 0;
		try {
			count = q.count();//获取查询的数据条数
		} catch (AVException e) {
			e.printStackTrace();
			if (e.getCode() == AVException.OBJECT_NOT_FOUND) {
				count = 0;
			} else {
				throw e;
			}
		}
		if (count > 0) {//若查询有数据，则表明已请求过了
			throw new Exception(
					App.ctx.getString(R.string.alreadyCreateAddRequest));
		} else {//若查询无数据，则创建该请求并将其保存到数据库表中
			AddRequest add = new AddRequest();
			add.setFromUser(curUser);
			add.setToUser(toUser);
			add.setStatus(AddRequest.STATUS_WAIT);
			add.save();
		}
	}

	// 开启一个新线程去创建一个添加好友的请求
	public static void createAddRequestInBackground(Context ctx,
			final AVUser user) {
		new SimpleNetTask(ctx) {
			@Override
			protected void doInBack() throws Exception {
				AddRequestService.createAddRequest(user);
			}

			@Override
			protected void onSucceed() {
				Utils.toast(R.string.sendRequestSucceed);
			}
		}.execute();
	}
}
